package com.HuangJiaQing.www.service.impl;

import com.HuangJiaQing.www.dao.CartMapper;
import com.HuangJiaQing.www.model.Cart;
import com.HuangJiaQing.www.dao.GoodsMapper;
import com.HuangJiaQing.www.model.CartExample;
import com.HuangJiaQing.www.model.Goods;
import com.HuangJiaQing.www.util.CartPlus;
import com.HuangJiaQing.www.model.User;
import com.HuangJiaQing.www.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HONOR
 * @date 2022/7/29 15:17
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private GoodsMapper goodsMapper;

    public String addCart(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        Cart cart = new Cart();
        cart.setGoodsId(id);
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getUserId());
        cart.setMarketerName(goods.getMarketersName());
        cartMapper.insertSelective(cart);
        return "redirect:/selectGoods/"+goods.getMarketersId();
    }

    public List<Cart> selectCartByUserId() {
        User user = (User) session.getAttribute("user");
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(user.getUserId());
        List<Cart> carts = cartMapper.selectByExampleWithGoods(cartExample);
        return carts;
    }

    public void updateGoodsNumber(Integer id, int number) {
        Cart cart = new Cart();
        cart.setCartId(id);
        cart.setGoodsNumber(number);
        cartMapper.updateByPrimaryKeySelective(cart);
    }

    public List<CartPlus> selectCartAndSort() {
        User user = (User) session.getAttribute("user");
        ArrayList<CartPlus> arrayList = new ArrayList<CartPlus>();
        List<Cart> carts = cartMapper.selectOnlyByUserId(user.getUserId());
        for (int i = 0; i < carts.size(); i++) {
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andMarketerNameEqualTo(carts.get(i).getMarketerName()).andUserIdEqualTo(user.getUserId());
            List<Cart> list = cartMapper.selectByExampleWithGoods(cartExample);
            CartPlus cartPlus = new CartPlus();
            cartPlus.setMarketerName(carts.get(i).getMarketerName());
            cartPlus.setCarts(list);
            arrayList.add(cartPlus);
        }
       return arrayList;
    }

    public void deleteCartById(Integer id) {
        cartMapper.deleteByPrimaryKey(id);
    }


}
